package com.dkd.service.impl;

import cn.elegent.token.context.ElegentTokenContext;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.client.entity.UserEntity;
import com.dkd.client.user.UserClient;
import com.dkd.dao.VendingMachineDao;
import com.dkd.entity.*;
import com.dkd.entity.dto.ApplyPolicyDto;
import com.dkd.entity.dto.RepairCountDto;
import com.dkd.entity.dto.VmDto;
import com.dkd.entity.dto.VmQuery;
import com.dkd.entity.vo.*;
import com.dkd.service.*;
import com.dkd.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class VendingMachineServiceImpl extends ServiceImpl<VendingMachineDao, VendingMachineEntity> implements VendingMachineService {
    private final UserClient userClient;
    private final VmTypeService vmTypeService;
    private final NodeService nodeService;
    private final VmPolicyService vmPolicyService;
    private final PolicyService policyService;
    private final ChannelService channelService;
    private final RegionService regionService;
    private final SkuService skuService;
    @Override
    @Transactional
    public List<VmVo> addVm(VmDto vmDto) {
        //设置插入数据库的信息
        VendingMachineEntity vm = new VendingMachineEntity();
        //设置插入数据库的售货机类型信息
        Integer vmTypeId = vmDto.getVmType();
        VmTypeEntity vmTypeEntity = vmTypeService.getById(vmTypeId);
        vm.setVmType(vmTypeId);
        vm.setInnerCode(vmTypeEntity.getInnerCode());
        //插入数据库的用户信息
        vm.setCreateUserId(0L);
        Long userId = Long.valueOf(ElegentTokenContext.getUserId());
        UserEntity user = userClient.getUserById(userId);
        if (user!=null){
            vm.setCreateUserId(userId);
            String userName = user.getUserName();
            vm.setCreateUserName(userName);
        }
        //插入数据库的node信息
        long nodeId = Long.parseLong(vmDto.getNodeId());
        vm.setNodeId(nodeId);
        NodeEntity nodeEntity = nodeService.lambdaQuery().eq(NodeEntity::getId, nodeId).one();
        if (nodeEntity!=null){
            vm.setOwnerName(nodeEntity.getOwnerName());
            vm.setOwnerId(nodeEntity.getOwnerId());
            vm.setLatitude(Double.parseDouble(nodeEntity.getLat()!=null ? nodeEntity.getLat():"0"));
            vm.setLongitudes(Double.parseDouble(nodeEntity.getLon()!=null ? nodeEntity.getLon():"0"));
            vm.setRegion(nodeEntity.getRegion());
            vm.setRegionId(nodeEntity.getRegionId());
            vm.setBusinessId(nodeEntity.getBusinessId());
        }
        vm.setInnerCode(UUIDUtils.getUUID());
        vm.setCreateTime(LocalDateTime.now());
        this.save(vm);
        //设置插入到货道的信息

        List<ChannelEntity> channelEntityList = vmDto.getChannelEntityList();
        if (channelEntityList!=null){
            for (ChannelEntity channelEntity : channelEntityList) {
                channelEntity.setInnerCode(vm.getInnerCode());
                channelEntity.setVmId(vm.getId());

            }
            channelService.saveBatch(channelEntityList);
        }
        //设置返回对象
        List<VmTypeEntity> vmTypeList = vmTypeService.lambdaQuery()
                .eq(VmTypeEntity::getTypeId, vmDto.getVmType())
                .list();
        List<VmVo> vmVos = new ArrayList<>();
        for (VmTypeEntity typeEntity : vmTypeList) {
            VmVo vmVo = new VmVo();
            BeanUtils.copyProperties(typeEntity, vmVo);
            vmVos.add(vmVo);
        }
        return vmVos;
    }

    @Override
    public void updateVm(Long id, Long nodeId) {
        this.lambdaUpdate()
                .setSql("node_id=" + nodeId)
                .eq(VendingMachineEntity::getId, id).update();

    }

    @Override
    @Transactional
    public boolean applyPolicy(ApplyPolicyDto applyPolicyDto) {
        //获取售货机编号列表
        List<String> innerCodeList = applyPolicyDto.getInnerCodeList();
        //获取售货机列表
        List<VendingMachineEntity> VendingMachineEntityList = this.lambdaQuery().in(VendingMachineEntity::getInnerCode, innerCodeList).list();
        //设置插入策略类型
        List<PolicyEntity> PolicyEntityList = policyService.lambdaQuery().eq(PolicyEntity::getPolicyId, applyPolicyDto.getPolicyId()).list();
        if (VendingMachineEntityList==null||PolicyEntityList==null){
            return false;
        }
        //设置机器和策略的关联列表
        ArrayList<VmPolicyEntity> vmPolicyEntities = new ArrayList<>(VendingMachineEntityList.size());
        //插入信息
        for (PolicyEntity policyEntity : PolicyEntityList) {
            for (VendingMachineEntity vendingMachineEntity : VendingMachineEntityList) {
                VmPolicyEntity vmPolicyEntity = new VmPolicyEntity();
                BeanUtils.copyProperties(policyEntity,vmPolicyEntity);
                vmPolicyEntity.setInnerCode(vendingMachineEntity.getInnerCode());
                vmPolicyEntity.setVmId(vendingMachineEntity.getId());
                vmPolicyEntities.add(vmPolicyEntity);
            }
        }
        return  vmPolicyService.saveBatch(vmPolicyEntities);
    }

    @Override
    public VmPageVo pageVm(VmQuery query) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        log.info("分页查询售货机列表");
        //设置分页查询结果
        VmPageVo vmPageVo = new VmPageVo();
        //设置分页信息
        Integer pageIndex = query.getPageIndex();
        Integer pageSize = query.getPageSize();
        Page<VendingMachineEntity> page = new Page<>(pageIndex, pageSize);
        //查询初始信息
        this.lambdaQuery()
                .eq(query.getStatus()!=null,VendingMachineEntity::getVmStatus,query.getStatus())
                .eq(query.getInnerCode()!=null,VendingMachineEntity::getInnerCode,query.getInnerCode())
                .page(page);
        //
        long totalCount = page.getTotal();//总个数
        long totalPage = totalCount / pageSize;//总页数
        //获取售货机列表信息
        List<VendingMachineEntity> VendingMachineEntityList = page.getRecords();
        //封装返回参数
        vmPageVo.setPageIndex(String.valueOf(pageIndex));
        vmPageVo.setPageSize(String.valueOf(pageSize));
        vmPageVo.setTotalPage(String.valueOf(totalPage));
        vmPageVo.setTotalCount(String.valueOf(totalCount));
        //设置返回列表
        ArrayList<VmPageItemVo> currentPageRecords = new ArrayList<>();

        for (VendingMachineEntity vm : VendingMachineEntityList) {

            VmPageItemVo vmPageItemVo = new VmPageItemVo();
            BeanUtils.copyProperties(vm,vmPageItemVo);
            //设置创建时间
            String format = vm.getCreateTime().format(formatter);
            vmPageItemVo.setCreateTime(format);
            String format2 = vm.getLastSupplyTime().format(formatter);
            vmPageItemVo.setLastSupplyTime(format2);
            //设置所属点位信息
            NodeEntity nodeEntity = nodeService.getById(vm.getNodeId());
            NodeItemVo nodeItemVo = new NodeItemVo();
            BeanUtils.copyProperties(nodeEntity, nodeItemVo);
            vmPageItemVo.setNodeItemVo(nodeItemVo);
            //设置	所属区域信息
            RegionEntity regionEntity = regionService.getById(vm.getRegionId());
            RegionItemVo regionItemVo = new RegionItemVo();
            BeanUtils.copyProperties(regionEntity, regionItemVo);
            //设置货道信息
            List<ChannelEntity> channelEntityList = channelService.lambdaQuery().eq(ChannelEntity::getInnerCode, vm.getInnerCode()).list();
            for (ChannelEntity channelEntity : channelEntityList) {
                SkuEntity skuEntity = skuService.getById(channelEntity.getSkuId());
                channelEntity.setSku(skuEntity);
            }
            vmPageItemVo.setChannelEntityList(channelEntityList);
            vmPageItemVo.setRegionItemVo(regionItemVo);
            //设置售货机类型
            VmTypeEntity vmTypeEntity = vmTypeService.getById(vm.getVmType());
            VmItemTypeVo vmItemTypeVo = new VmItemTypeVo();
            BeanUtils.copyProperties(vmTypeEntity, vmItemTypeVo);
            vmPageItemVo.setVmItemTypeVo(vmItemTypeVo);
            //合作商名称
            vmPageItemVo.setOwnerName(vm.getOwnerName());
            //status
            vmPageItemVo.setStatus(vm.getStatus());
            currentPageRecords.add(vmPageItemVo);
        }
        vmPageVo.setCurrentPageRecords(currentPageRecords);
        return vmPageVo;
    }

    @Override
    public List<VendingMachineEntity> repairCount(RepairCountDto repairCountDto) {

        return   this.lambdaQuery().eq(repairCountDto.getNodeId()!=null,VendingMachineEntity::getNodeId,repairCountDto.getNodeId()).eq(repairCountDto.getVmType()!=null,VendingMachineEntity::getVmType,repairCountDto.getVmType()).eq(repairCountDto.getCreateUserId()!=null,VendingMachineEntity::getCreateUserId,repairCountDto.getCreateUserId()).list();
    }

    @Override
    public boolean updateStatus(Long vmId, Integer status) {

        return this.lambdaUpdate().eq(VendingMachineEntity::getId,vmId).setSql(status!=null,"vm_status="+status).update();
    }

    @Override
    public VendingMachineEntity getDetails(String innerCode) {
        VendingMachineEntity vm= this.lambdaQuery().eq(VendingMachineEntity::getInnerCode, innerCode).one();
        //设置类型信息
        Integer vmType = vm.getVmType();
        VmTypeEntity vmTypeEntity = vmTypeService.getById(vmType);
        vm.setType(vmTypeEntity);
        //设置渠道信息
        Long vmId = vm.getId();
        List<ChannelEntity> channelEntityList = channelService.lambdaQuery().eq(ChannelEntity::getVmId, vmId).list();
        vm.setChannelEntityList(channelEntityList);
        //设置点位信息
        Long nodeId = vm.getNodeId();
        NodeEntity nodeEntity = nodeService.getById(nodeId);
        vm.setNode(nodeEntity);
        //设置区域信息
        Long regionId = vm.getRegionId();
        RegionEntity regionEntity = regionService.getById(regionId);
        vm.setRegion(regionEntity);

        return vm;
    }
}
